package org.chen.wordwave.fragment;

import static com.blankj.utilcode.util.ViewUtils.runOnUiThread;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.hjq.toast.ToastParams;
import com.hjq.toast.Toaster;
import com.hjq.toast.style.CustomToastStyle;

import org.chen.wordwave.Api.ApiClient;
import org.chen.wordwave.Api.ApiService;
import org.chen.wordwave.R;
import org.chen.wordwave.act.Login;
import org.chen.wordwave.bean.SignIn;
import org.chen.wordwave.bean.UserInfo;
import org.chen.wordwave.init.WordInit;
import org.chen.wordwave.tools.calendar.WordCalendar;
import org.chen.wordwave.tools.user.UserUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class DakaFragment extends Fragment {
    private WordCalendar calendar_daka;
    private TextView tv_lxqd, tv_ljqd,jifen;
    private Button btn_punch;
    private UserInfo currentUser;
    private ApiService apiService;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        apiService = ApiClient.getClient(getContext()).create(ApiService.class);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.fragment_daka, null);
        tv_ljqd = view.findViewById(R.id.tv_ljqd);
        tv_lxqd = view.findViewById(R.id.tv_lxqd);
        jifen = view.findViewById(R.id.jifen);
        calendar_daka = view.findViewById(R.id.calendar_daka);
        btn_punch = view.findViewById(R.id.btn_punch);

        // 获取当前用户
        currentUser = getCurrentUser();

        if (currentUser == null) {
            // 处理用户未登录的情况
            // 例如：跳转到登录页面
            startActivity(new Intent(getContext(), Login.class));
            requireActivity().finish();
        }

        // 检查今天是否已经打卡
        String today = getToday();

        updateDays();

        btn_punch.setOnClickListener((e) -> {
            btn_punch.setEnabled(false);
            Log.d("DakaFragment", "打卡成功");
            int totalSignInDays = currentUser.getTotalSignInDays() + 1;
            int consecutiveSignInDays = currentUser.getConsecutiveSignInDays() + 1;
            currentUser.setTotalSignInDays(currentUser.getTotalSignInDays() + 1);
            currentUser.setConsecutiveSignInDays(currentUser.getConsecutiveSignInDays() + 1);
            currentUser.setLastSignInDate(today);
            currentUser.setPoints(currentUser.getPoints() + 100);
            if (currentUser.getSignedInDates() == null) {
                currentUser.setSignedInDates(new ArrayList<>());
            }
            currentUser.getSignedInDates().add(today);
            // 检查累计签到天数
            if (totalSignInDays % 10 == 0) {
                currentUser.setPoints(currentUser.getPoints() + 1000);
                currentUser.setLuckyDrawBtn(currentUser.getLuckyDrawBtn() + 4);
                String message = String.format(getString(R.string.sign_in_message), totalSignInDays);
                Toaster.show(message);
            }

            // 检查连续签到天数
            if (consecutiveSignInDays % 20 == 0) {
                currentUser.setPoints(currentUser.getPoints() + 2000);
                currentUser.setLuckyDrawBtn(currentUser.getLuckyDrawBtn() + 9);
                String message = String.format(getString(R.string.consecutive_sign_in_message), consecutiveSignInDays);
                Toaster.show(message);
            }
            currentUser.setLuckyDrawBtn(currentUser.getLuckyDrawBtn() + 1);
            currentUser.saveOrUpdate("email = ?", currentUser.getEmail());
            calendar_daka.updateSignInStatus(currentUser);
            Log.e("DakaFragment",currentUser.toString());
            SignIn signIn = new SignIn(WordInit.userInfo.getEmail(),currentUser.getTotalSignInDays(),currentUser.getConsecutiveSignInDays(),currentUser.getLastSignInDate(),currentUser.getPoints(),currentUser.getLuckyDrawBtn());
            new Thread(() -> {
                runOnUiThread(() -> {
                    apiService.SignIn(signIn).enqueue(new Callback<SignIn>() {
                        @Override
                        public void onResponse(Call<SignIn> call, Response<SignIn> response) {
                            if (response.isSuccessful() && response.body() != null) {
                                btn_punch.setEnabled(false);
                                btn_punch.setText(R.string.singin);
                                updateDays();
                                ToastParams toastParams = new ToastParams();
                                toastParams.style = new CustomToastStyle(R.layout.success);
                                toastParams.text = getString(R.string.SUCCESSFUL_CHECK_IN);
                                Toaster.show(toastParams);
                            }else{
                                ToastParams toastParams = new ToastParams();
                                toastParams.style = new CustomToastStyle(R.layout.error);
                                toastParams.text = getString(R.string.SIGN_IN_FAILED);
                                Toaster.show(toastParams);
                                btn_punch.setEnabled(true);
                            }
                        }

                        @Override
                        public void onFailure(Call<SignIn> call, Throwable t) {
                            ToastParams toastParams = new ToastParams();
                            toastParams.style = new CustomToastStyle(R.layout.error);
                            toastParams.text = getString(R.string.SIGN_IN_FAILED);
                            Toaster.show(toastParams);
                            btn_punch.setEnabled(true);
                        }
                    });
                });
            }).start();
        });

        return view;
    }

    @NonNull
    private String getToday() {
        String today = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
        String lastPunchDate = currentUser.getLastSignInDate();
        if (today.equals(lastPunchDate)) {
            btn_punch.setEnabled(false);
            btn_punch.setText(R.string.singin);
        }else {
            btn_punch.setEnabled(true);
            btn_punch.setText(R.string.i_sigin_up);
        }
        return today;
    }

    private UserInfo getCurrentUser() {
        Log.e("打卡","获取用户");
        return UserUtils.getCurrentUser(getContext());
    }

    private void updateDays() {
        if (currentUser != null) {
            tv_ljqd.setText(String.valueOf(currentUser.getTotalSignInDays()));
            tv_lxqd.setText(String.valueOf(currentUser.getConsecutiveSignInDays()));
            jifen.setText(String.valueOf(currentUser.getPoints()));
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        currentUser = getCurrentUser();
        Log.d("DakaFragment", "刷新积分"+currentUser);
        updateDays();
        getToday();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            currentUser = getCurrentUser(); // 重新获取当前用户
            Log.d("DakaFragment", "Fragment重新显示"+currentUser);
            updateDays();
            getToday();
        }
    }
}
